#!/bin/bash

# Copyright (C) Metaswitch Networks 2016
# If license terms are provided to you in a COPYING file in the root directory
# of the source code repository by which you are accessing this code, then
# the license outlined in that COPYING file applies to your use.
# Otherwise no rights are granted except for those provided to you by
# Metaswitch Networks in a separate written agreement.
if [ -z $1 ]
then
  echo "You must provide a location to backup the configuration to"
  echo
  echo "Usage: $0 backup_directory"
  exit 1
fi

local_site_name=site1
etcd_key=clearwater
. /etc/clearwater/config

backup_directory=$1

top_key=/${etcd_key}/${local_site_name}/configuration/

clearwater-etcdctl ls ${top_key} > /tmp/backup_config.$$.stdout 2> /tmp/backup_config.$$.stderr
rc=$?

if [ $rc != 0 ] ; then
  echo "Failed to list keys from etcd config with return code $rc" >&2
  cat /tmp/backup_config.$$.stderr                                 >&2
  exit 2
fi

while read -r full_key; do
  key=${full_key/$top_key/}
  if [[ "$key" != apply_* ]]; then
    backup_file=${backup_directory}/$key

    clearwater-etcdctl get $full_key > "${backup_file}" 2> /tmp/backup_config.$key.$$

    rc=$?

    # Check the return code and log if appropriate.
    if [ $rc != 0 ] ; then
      echo "Failed to get $full_key from etcd config with return code $rc" >&2
      cat /tmp/backup_config.$key.$$              >&2
      exit 3
    fi
  fi
done < /tmp/backup_config.$$.stdout

rm /tmp/backup_config.$$.stderr
rm /tmp/backup_config.$$.stdout
